package com.acme.bankapp.service;

import java.io.*;

import com.acme.bankapp.domain.*;
import com.acme.bankapp.exceptions.ClientExistsException;
import com.acme.bankapp.exceptions.NotEnoughFundsException;
import com.acme.bankapp.exceptions.SavingDataFailure;
import java.util.*;

public class BankService {
	static public void addClient(Bank bank, Client client)
			throws ClientExistsException, SavingDataFailure {
		bank.addClient(client);
		BankService.saveBank(bank, "saving.txt");
	}

	public static void modifyBank(Bank bank, double amount)
			throws NotEnoughFundsException {
		Set<Client> clis = bank.getClients();

		for (Client client : clis) {
			Set<Account> accs = client.getAccounts();
			for (Account account : accs) {
				account.withdraw(amount);
				account.deposit(amount);
			}

		}
	}

	public static void printBalance(Bank bank) {
		Set<Client> clis = bank.getClients();

		for (Client client : clis) {
			System.out.println(client);

		}
	}

	public static void printMaximumAmountToWithdraw(Bank bank) {
		Set<Client> clis = bank.getClients();

		for (Client client : clis) {
			Set<Account> accs = client.getAccounts();
			for (Account account : accs) {
				System.out.println(" Maxium to withdraw: "
						+ account.maximumAmountToWithdraw());

			}

		}
	}

	public static void saveBank(Bank bank, String pathTo)
			throws SavingDataFailure {
		ObjectOutputStream ois;
		try {
			ois = new ObjectOutputStream(new FileOutputStream(pathTo));
			ois.writeObject(bank);
			ois.close();
		} catch (FileNotFoundException e) {
			throw new SavingDataFailure();
		} catch (IOException e) {
			throw new SavingDataFailure();
		}

	}

	public static Bank readBank(String pathFrom) throws FileNotFoundException,
			IOException, ClassNotFoundException {
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
				pathFrom));
		Bank bank = (Bank) ois.readObject();
		ois.close();
		return bank;

	}
}
